/*
 * $Id: ImageCaptchaServlet.java 16 2014-08-22 10:12:14Z ratking $
 *
 * Copyleft (C) 2014 RatKing. All wrongs reserved.
 */
package cn.ratking.demo.jaws6.security.servlet;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.octo.captcha.service.CaptchaServiceException;
import org.slf4j.Logger;

/**
 * 生成JCaptcha验证码图片
 *
 * @see https://jcaptcha.atlassian.net/wiki/display/general/5+minutes+application+integration+tutorial
 */
@WebServlet(name = "ImageCaptchaServlet", urlPatterns = {"/resources/images/jcaptcha.png"})
public class ImageCaptchaServlet extends HttpServlet {

    @Inject
    private transient Logger log;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        byte[] captchaChallengeAsPng = null;
        // the output stream to render the captcha image
        ByteArrayOutputStream captchaOutputStream = new ByteArrayOutputStream();
        try {
            // get the session id that will identify the generated captcha.
            //the same id must be used to validate the response, the session id is a good candidate!
            String captchaId = request.getSession().getId();
            // call the ImageCaptchaService getChallenge method
            BufferedImage challenge = CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId, request.getLocale());
            if (ImageIO.write(challenge, "png", captchaOutputStream)) {
                //stream = new ByteArrayInputStream(captchaOutputStream.toByteArray());
            } else {
                throw new IOException("找不到合适png的writer");
            }
        } catch (IllegalArgumentException iae) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (IOException ioe) {
            String errorMsg = "内部异常：生成图片验证码时IO异常" + ioe.getMessage();
            log.error(errorMsg, ioe);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        } catch (CaptchaServiceException cse) {
            String errorMsg = "内部异常：生成图片验证码时IO异常" + cse.getMessage();
            log.error(errorMsg, cse);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        captchaChallengeAsPng = captchaOutputStream.toByteArray();
        // flush it in the response
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        out.write(captchaChallengeAsPng);
        out.flush();
        out.close();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "ImageCaptchaServlet";
    }// </editor-fold>
}
